<template>
  <div>

    <el-input type="textarea" :rows="8" v-model="text" placeholder="点击开始进行语音识别"></el-input>
    <el-button @click="startButton()">开始识别</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      recognition: false,
      text: ''
    };
  },
  created() {
    this.initRecognition()
  },
  methods: { 
    startButton() { 
      if (this.recognizing) {
        this.recognition.stop();
        return;
      }
      this.recognition.start();
    },
    initRecognition() {
      if (!('webkitSpeechRecognition' in window)) {
        alert('你的浏览器不支持语音识别')
        return
      } else {
        this.recognition = new webkitSpeechRecognition()
        this.recognition.continuous = false;
        this.recognition.interimResults = false;
        this.recognition.onstart = (event) => {
          this.recognizing = true;
        };
        this.recognition.onerror = (event) => {
          this.$message.error(event.error)
        };
        this.recognition.onend = (event) => {
          this.recognizing = false;
        };
        this.recognition.onresult = (event) => {
          if (typeof (event.results) == 'undefined') {
          this.recognition.onend = null;
          this.recognition.stop();
          return;
        }
        const transcript = event.results[event.resultIndex][0].transcript.trim();
        this.text = transcript
        };
      }
    },
  }
};
</script>

<style scoped>
/* 您可以在此处添加样式 */
</style>
